﻿using HostAssistantCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HostAssistant
{
    public partial class addsites : U1Form
    {
        public addsites()
        {
            InitializeComponent();
            txtspath.ReadOnly = true;
            chkyes.Properties.RadioGroupIndex = 1;
            chkyes.Checked = true;
            chkno.Properties.RadioGroupIndex = 1;
            txtphppath.Visible = simpleButton4.Visible = false;
            txtphppath.ReadOnly = true;
            lblhid.Visible = false;
        }
        private void addsites_Load(object sender, EventArgs e)
        {
            this.txtspath.Text = System.Configuration.ConfigurationManager.AppSettings.Get("sitepath");
                ftppwd.Text = Guid.NewGuid().ToString().Substring(0, 6);

            TextBoxToolV2.SetWatermark(txtcpu, "不限CPU");

            TextBoxToolV2.SetWatermark(txtdk, "不限带宽");

            TextBoxToolV2.SetWatermark(txtljs, "不限连接数");

            TextBoxToolV2.SetWatermark(txtnc, "不限内存");
            netv();


        }

        /// <summary>
        /// 获取net版本
        /// </summary>
        void netv()
        {
            cmbv.Properties.Items.Clear();
          
            string netv2 = "";
            string netv4 = "";

            try
            {
                var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
                foreach (string keyname in key.GetSubKeyNames())
                {
                    string netversion = keyname.Substring(0, 2);
                    if (netversion == "v2")
                    {

                        netv2 = "v2.0.50727";
                    }
                    if (netversion == "v4")
                    {
                        try
                        {
                            netv4 = "v" + Environment.Version.ToString();

                        }
                        catch (Exception ex)
                        {
                            NLogger.Error(ex.ToString());
                        }
                    }
                    if (netv2 == "" && netv4 == "")
                    {
                        DirectoryInfo NetFolder = new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework");
                        //遍历文件夹
                        foreach (DirectoryInfo sonFolder in NetFolder.GetDirectories())
                        {
                            if (sonFolder.Name.Contains("v2.0"))
                            {
                                netv2 = "v2.0.50727";
                            }
                        }
                        netv4 = "v" + Environment.Version.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                DirectoryInfo NetFolder = new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework");
                //遍历文件夹
                foreach (DirectoryInfo sonFolder in NetFolder.GetDirectories())
                {
                    if (sonFolder.Name.Contains("v2.0"))
                    {
                        netv2 = "v2.0.50727";
                    }
                }
                netv4 = "v" + Environment.Version.ToString();
            }
            if (netv2.Trim().ToString() != "")
            {



                cmbv.Properties.Items.Add(netv2);
                cmbv.Text = netv2;

            }
            if (netv4.Trim().ToString() != "")
            {

                cmbv.Properties.Items.Add(netv4);

                if (cmbv.Text == "")
                    cmbv.Text = netv4;
            }
        }

        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {

          
            this.Dispose();
        }

        /// <summary>
        /// 选择路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                txtspath.Text = foldPath;


            }
        }

        private void txtsname_EditValueChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrWhiteSpace(txtsname.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("站点名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtspath.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("物理路径不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtdm.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("绑定域名不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            if (string.IsNullOrWhiteSpace(txtsy.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("默认首页不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (cstatus.Text == "PHP")
            {
                if (string.IsNullOrWhiteSpace(txtphppath.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("PHP路径不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }


                if (!File.Exists(txtphppath.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("PHP文件不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }


            if (chkyes.Checked)
            {
              

                if (string.IsNullOrWhiteSpace(ftppwd.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("FTP名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }


            try
            {

                Addmssql();
              //  OpHelper.CallWithTimeout(Addmssql, 10000);

            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                if (lblhid.Text == "1")
                {
                    lblhid.Text = "0";
                    Form1 f1 = (Form1)this.Owner;
                    f1.op("站点列表");
                    this.Dispose();
                }

            }





            
        }


        void Addmssql()
        {
            splashScreenManager1.ShowWaitForm();
            splashScreenManager1.SetWaitFormCaption("请等待");
            splashScreenManager1.SetWaitFormDescription("加载中...");
            //获取用户输入

            SiteInfo siteinfo = new SiteInfo();
            siteinfo.SiteName = this.txtsname.Text.Trim().ToString();//站点名
            siteinfo.PhysicalPath = this.txtspath.Text.Trim().ToString();//物理路径
            siteinfo.HttpPort = 80;//端口
            siteinfo.LogPath = siteinfo.PhysicalPath;

            //处理用户输入域名

            List<string> bindings = new List<string>();
            string[] cbindings = this.txtdm.Text.Split(",".ToCharArray());
            foreach (string binding in cbindings)
            {
                int length = binding.Split(":".ToCharArray()).Length;
                if (length == 1)
                {
                    bindings.Add(binding + ":" + siteinfo.HttpPort);
                }
                else
                {
                    bindings.Add(binding);
                }
            }

            // 获取ftp账号密码

            if (chkyes.Checked)
            {
                siteinfo.Ftpuser = this.txtsname.Text.Trim().ToString();
                siteinfo.Ftpass = this.ftppwd.Text.Trim().ToString();
                siteinfo.Password = this.ftppwd.Text.Trim().ToString();//密码
            }
            else//如果用户不设置FTP那么用户密码为用户名
            {
                siteinfo.Ftpuser = "";
                siteinfo.Ftpass = "";
                siteinfo.Password = System.Configuration.ConfigurationManager.AppSettings.Get("defaultpassword");
            }

            // 获取net版本

            string netversion = cmbv.Text;
            if (cstatus.Text == "PHP")
            {
                siteinfo.NetVersion = "";
            }
            else
            {
                string next = netversion.Substring(0, 4);
                siteinfo.NetVersion = netversion.Substring(0, 4);
                string version = siteinfo.NetVersion;
            }

            //// 获取PHP路径

            if (string.IsNullOrWhiteSpace(this.txtphppath.Text))
            {
                siteinfo.Phppath = "";
            }
            else
            {
                siteinfo.Phppath = this.txtphppath.Text.ToString();
              
            }

            //处理用户输入默认首页

            List<string> defaultDocuments = new List<string>();
            string pages = this.txtsy.Text.Trim().ToString();
            if (pages != "")
            {
                string[] homepages = pages.Split(",".ToArray());
                foreach (string defaultDocument in homepages)
                {
                    defaultDocuments.Add(defaultDocument);
                }
            }
            siteinfo.DefaultDocuments = defaultDocuments;
            siteinfo.Bindings = bindings;//绑定域名+端口
            siteinfo.Username = this.txtsname.Text.Trim().ToString();//用户名
            if (!string.IsNullOrWhiteSpace(this.txtdk.Text))
            {
                long tmaxbands = Convert.ToInt64(this.txtdk.Text.Trim());
                if (tmaxbands > 4095)
                {
                    siteinfo.MaxBandwidth = "0";
                }
                else
                {
                    siteinfo.MaxBandwidth = this.txtdk.Text.Trim();//最大带宽
                }
            }
            else
            {
                siteinfo.MaxBandwidth = "0";
            }
            if (!string.IsNullOrWhiteSpace(this.txtljs.Text))
            {
                long tmaxconnections = Convert.ToInt64(this.txtljs.Text.Trim());
                if (tmaxconnections > 4294967295)
                {
                    siteinfo.MaxConnections = "0";
                }
                else
                {
                    siteinfo.MaxConnections = this.txtljs.Text.Trim(); //最大连接数
                }
            }
            else
            {
                siteinfo.MaxConnections = "0";
            }
            if (!string.IsNullOrWhiteSpace(this.txtcpu.Text))
            {
                siteinfo.Cpulimit = this.txtcpu.Text.Trim(); ;//最大CPU
            }
            else
            {
                siteinfo.Cpulimit = "0";
            }
            if (!string.IsNullOrWhiteSpace(this.txtnc.Text))
            {
                siteinfo.Memeroy = this.txtnc.Text.Trim();//最大Memeory
                string y = this.txtnc.Text;
                string x = siteinfo.Memeroy;
            }
            else
            {
                siteinfo.Memeroy = "0";
            }
            siteinfo.Sstate = "off";
            siteinfo.Sstype = "site";
            string[] sxx = { "1" };

            NLogger.Info(JsonHelper.SerializeObject(siteinfo));
            int errorCode = ErrorCode.Succeed;
            errorCode = new IISManager().Manager(new string[] { "CREATESITE", "oh" }, siteinfo);



            if (errorCode == ErrorCode.Succeed)
            {
                if (chkyes.Checked)
                {
                    //string insert_sql = "insert into Ftpsite(Name,Pwd,OperPower,Path,CreTime,iisversion) values(@Name,@Pwd,@OperPower,@Path,@CreTime,@iisversion)";       //插入的SQL语句(带参数)
                    //Ftpsite Ftpsite = new Ftpsite();

                    //Ftpsite.Name = siteinfo.SiteName;

                    //Ftpsite.Pwd = siteinfo.Password;

                    //Ftpsite.Path = siteinfo.PhysicalPath;

                    //Ftpsite.CreTime = DateTime.Now.ToString();

                    //Ftpsite.OperPower = "读写";
                    //Data<Ftpsite>.GetInstance().Add(insert_sql, Ftpsite);


                    //string update_sql = "update Sites set  ftpname=@ftpname where  sname=@sname ";
                    //Sites Sites = new Sites();
                    //Sites.ftpname = siteinfo.SiteName;
                    //Sites.sname = siteinfo.SiteName;
                    //Data<Sites>.GetInstance().Update(update_sql, Sites);

                }
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show("创建成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                lblhid.Text = "1";
            }

            else
            {
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show(ErrorCode.getResult(errorCode), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            return;
        }
            /// <summary>
            /// 随机密码
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void simpleButton5_Click(object sender, EventArgs e)
        {
            ftppwd.Text = Guid.NewGuid().ToString().Substring(0, 6);

        }

      

        /// <summary>
        /// 是否ftp
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            if(chkyes.Checked==true)
            {
                simpleButton1.Top= simpleButton2.Top = 489;
                 ftppwd.Text = "";

                labelControl15.Visible =
              labelControl14.Visible = labelControl13.Visible =
              ftppwd.Visible = simpleButton5.Visible = true;
            }

            if (chkno.Checked == true)
            {


                simpleButton1.Top = simpleButton2.Top = 400;
               ftppwd.Text = "";

                labelControl15.Visible  =
                labelControl14.Visible = labelControl13.Visible =
                ftppwd.Visible = simpleButton5.Visible = false;
            }

        }

        /// <summary>
        /// 类型切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cstatus_SelectedValueChanged(object sender, EventArgs e)
        {
           

            if(cstatus.Text=="PHP")
            {
                cmbv.Properties.Items.Clear();
                cmbv.Properties.Items.Add("5.2");
                cmbv.Text = "5.2";
                cmbv.Properties.Items.Add("5.3");
                cmbv.Properties.Items.Add("5.4");
                cmbv.Properties.Items.Add("5.6");

                txtphppath.Visible = simpleButton4.Visible = true;

                txtphppath.Text = "";

                txtphppath.Text = @"C:\php\php" + cmbv.Text.Replace(".", "") + @"\php-cgi.exe";

            }
            else
            {
             
                netv();


                txtphppath.Visible = simpleButton4.Visible = false;

                txtphppath.Text = "";
            }

        }

        /// <summary>
        /// 选择php cgi exe  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {

            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*exe*)|*.exe*"; //设置要选择的文件的类型
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName;//返回文件的完整路径                
                txtphppath.Text = file;

            }

        }

        private void comboBoxEdit1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cstatus.Text == "PHP")
            {
                txtphppath.Text = @"C:\php\php"+ cmbv .Text.Replace(".","")+ @"\php-cgi.exe";
            }

               
            }

        private void txtcpu_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                e.Handled = false;
            }
        }

        private void txtdk_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                e.Handled = false;
            }
        }

        private void txtljs_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                e.Handled = false;
            }
        }

        private void txtnc_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                e.Handled = false;
            }
        }

        private void txtsname_MouseLeave(object sender, EventArgs e)
        {
            string s = System.Configuration.ConfigurationManager.AppSettings.Get("sitepath");


            if (this.txtspath.Text.ToLower() == System.Configuration.ConfigurationManager.AppSettings.Get("sitepath").ToLower())
            {
                this.txtspath.Text = System.Configuration.ConfigurationManager.AppSettings.Get("sitepath") + "\\" + this.txtsname.Text + "\\wwwroot";
            }
            else
            {
                if (this.txtspath.Text.Contains(s))
                {
                    this.txtspath.Text = System.Configuration.ConfigurationManager.AppSettings.Get("sitepath") + "\\" + this.txtsname.Text + "\\wwwroot";

                }
            }
        }
    }
}
